<?php

class User_Form_RegisterBusinessInfoForm extends Ac_Form
{

    /**
     *
     * @var Model_User empty user with properly setted behavior
     */
    private $_user;

    protected $elementButtonDecorators = array(
        'ViewHelper',
        'Errors',
    );

    protected $elementDecorators = array(
        'ViewHelper',
        'Errors',
    );

    protected $formDecorators = array(
            'PrepareElements',
            array('ViewScript', array('viewScript' => 'index/register-business-dir-info.phtml'))
    );

    protected $subFormDecorators = array(
        'FormElements',
        array('Description', array('escape' => false, 'placement' => 'PREPEND')),
        'fieldset',
    );

    protected $spanDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'prepend')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );

    protected $displayGroupDecorators = array(
        'FormElements',
    );

    protected $elementSelectDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array()),
        array(array('row' => 'HtmlTag'), array('class'=>'select')),
    );

	public function __construct($options = array())
    {
        parent::__construct();
    }
    
    function setUser($user)
    {
        $this->_user = $user;
    }
    
    /**
     * define form elements
     */
    public function init()
    {
        parent::init();

        $this->setMethod('post');
        $this->setAction($this->getView()->geturl('register-business-info' ,'user'));
        $this->initBusinessInfo();
    }

    private function initBusinessInfo()
    {
        /* Company Name (username) */
        $this->addElement('text', 'company_name', array(
            'description' => '4-30个字符',
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请填写信息')),
                array('StringLength', true, array(4, 30, 'messages' => '4-30个字符')),
            ),
            'decorators' => $this->elementDecorators,
            'required'   => true,
        ));
        
        /* phone */
        $this->addElement('text', 'company_phone', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'description' => 'Primary contact number for your company',
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请填写信息')),
                array('int', false, array('messages' => array(Zend_Validate_Int::NOT_INT =>'請填寫數'))),
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Company Phone',
        ));

        /* fax */
        $this->addElement('text', 'company_fax', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'description' => 'Primary contact number for your company',
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请填写信息')),
                array('int', false, array('messages' => array(Zend_Validate_Int::NOT_INT =>'請填寫數'))),
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Company Fax',
        ));

        /* number employees */
        $this->addElement('text', 'number_employees', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'description' => 'Number of employees in the company',
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请填写信息')),
                array('int', false, array('messages' => array(Zend_Validate_Int::NOT_INT =>'請填寫數'))),
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Number of employees',
        ));


        // Business Category
        $this->addElement('select', 'business_category', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
                 array('NotEmpty', true, array('messages' => '请填写信息')),
            ),
            'decorators'   => $this->elementDecorators,
            'multiOptions' => Model_Company::getBusinessCategory(),
            'required'     => true,
        ));
        
        if (empty($_POST['area_l1'])) {
            $selected_area = 0;
            if (!empty($this->_listing)) {
                $selected_area = $this->_listing->area_l1;
                if (empty($selected_area)) {
                    $loc = $this->_listing->area_l2;
                    if (!empty($loc)) {
                        $selected_area = (string)$loc->getParent()->_id;
                    }
                }
            }
        }
        else {
            $selected_area = $_POST['area_l1'];
        }
        $areas = Model_Location::getAreaL1PostAd();
        if (empty($selected_area)) {
            reset($areas);
            $selected_area = key($areas);
        }
        $this->addElement('select', 'area_l1', array(
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请在下拉菜单选择一个选项，不能为空')),
            ),
            'multiOptions' => $areas,
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => true,
        ));

        //District
        $this->addElement('select', 'area_l2', array(
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请在下拉菜单选择一个选项，不能为空')),
            ),
            'multiOptions' => Model_Location::getAreaL2PostAd($selected_area),
            //'disableLoadDefaultDecorators' => true,
            //'decorators' => $this->elementDecorators,
            'decorators'   => array(
                'ViewHelper',
                //'Errors',
                array('Label', array()),
            ),
            'required'   => false,
        ));


		
        /*mailling address */
        $this->addElement('text', 'company_mail_address', array(
            'filters'    => array('StringTrim'),
            'label'      => 'Mailling Address',
            'decorators' => $this->elementDecorators,
        ));

        /* Company Website */
        $this->addElement('text', 'company_website', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
            ),
            'decorators' => $this->elementDecorators,
            'label'      => 'Company Website',
        ));
    
         /* Company weibo */
        $this->addElement('text', 'company_weibo', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
            ),
            'decorators' => $this->elementDecorators,
            'label'      => 'Company Weibo',
        )); 
		
		$this->addElement('text', 'contact_messenger', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
            ),
            'decorators' => $this->elementDecorators,
            'label'      => 'MSN/QQ',
        ));

       //$form = $this->getNewSubForm();
        //$form->setDecorators($this->subFormDecorators);

        /* Name */
        $this->addElement('text', 'contact_name', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'decorators' => $this->elementDecorators,
            'required'   => true,
            'label'      => 'Name',
        ));
		
		//$form->lastname->addDecorator('HtmlTag', array('tag'=>'div', 'closeOnly'=>true, 'placement'=>'APPEND'));
		
        /* Department */
        $this->addElement('text', 'contact_department', array(
            'filters'    => array('StringTrim'),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Department',
        ));
		
		//$form->department->addDecorator('HtmlTag', array('tag'=>'div', 'class'=>'text col_cut_2', 'openOnly'=>true, 'placement'=>'PREPEND'));
		
        /* Job Title */
        $this->addElement('text', 'contact_job_title', array(
            'filters'    => array('StringTrim'),
           	'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Job Title',
        ));
		
		//$form->job_title->addDecorator('HtmlTag', array('tag'=>'div', 'closeOnly'=>true, 'placement'=>'APPEND'));
		
        /* Phone */
        $this->addElement('text', 'contact_phone', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('int', false, array('messages' => array(Zend_Validate_Int::NOT_INT =>'請填寫數'))),
            ),
            'decorators' => $this->elementDecorators,
            'required'   => true,
            'label'      => 'Mobile Phone',
        ));

        /* Email */
        $this->addElement('text', 'contact_email', array(
            'filters'    => array('StringTrim'),
            'description' => "e.g info@companyabc.com",
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请填写信息')),
                array('EmailAddress', true, array('messages' => array(Zend_Validate_EmailAddress::INVALID_FORMAT => '請填寫有效電郵地址'))),
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => '電郵地址',
        ));

        /* about us */
        $this->addElement('textarea', 'about_us', array(
            'filters'    => array('StringTrim'),
            'label'      => 'About Us',
            'decorators' => $this->elementDecorators,
        ));
        
        /* Submit Button */
        $this->addElement('button', 'get_listed', array(
            'required'    => false,
            'ignore'      => true,
            'type'        => 'submit',
            'label'       => 'Get Listed',
            'decorators' => $this->elementDecorators,
        ));
		        
    }
    
    public function isValidPartial(array $post = array())
    {
        $test = parent::isValidPartial($post);
        return $this->validate($post) & $test;
    }
    /**
     *
     * @param array $post
     */
    public function isValid($post = array())
    {
        $test = parent::isValid($post);
        return $this->validate($post) & $test;
    }
    
    /**
     *
     * @param array $post
     */
    public function validate($post = array())
    {
        
        $test = true;

        //TODO: check if company exists
        if (!empty($post['company_name'])) {
            $num = Model_Company::one(array('username' => $post['company_name']));
            if (!empty($num)) {
                $this->getElement('company_name')->addError($post['company_name'].'已經被使用');
                $test = false;
            }
        }
        
        return $test;
    }

    public function populate(array $arr)
    {
        if (empty($_POST)) {
            $user = Zend_Registry::get('loggedin_user');
            $this->getElement('contact_email')->setValue($user->email);
        }

        if (empty($_POST['company_weibo'])) {
            $this->getElement('company_weibo')->setValue('http://');
        }

        if (empty($_POST['company_website'])) {
            $this->getElement('company_website')->setValue('http://');
        }
    }

    public function save()
    {

        $c = $this->_user->company;
        $c->company_name        = $_POST['company_name'];
        $c->username            = $_POST['company_name'];
        $c->mailing_address     = $_POST['company_mail_address'];
        $c->phone               = $_POST['company_phone'];
        $c->fax                 = $_POST['company_fax'];
        $c->website             = ($_POST['company_website'] == 'http://' || $_POST['company_website'] == '')? '' : $_POST['company_website'];
        if (!empty($_POST['business_category'])) {
            $c->business_category   = new MongoId($_POST['business_category']);
        }
        $c->location      = (!empty($_POST['area_l2']) && $_POST['area_l2']!=0) ? new MongoId($_POST['area_l2']) : null ;

        $c->weibo = ($_POST['company_weibo'] == 'http://' || $_POST['company_weibo'] == '')? '' : $_POST['company_weibo'];
		
        //fill biz contact
        $c->contact_name           = $_POST['contact_name'];
        $c->contact_department     = $_POST['contact_department'];
        $c->contact_job            = $_POST['contact_job_title'];
        $c->contact_phone          = $_POST['contact_phone'];
        $c->contact_email          = $_POST['contact_email'];
        $c->contact_messenger      = $_POST['contact_messenger'];
        $c->number_employees       = $_POST['number_employees'];

        $user = Zend_Registry::get('loggedin_user');
        $user->username = $_POST['company_name'];
        $user->phone = $_POST['contact_phone'];
        $user->save();

        //fill biz about us
        $c->about     			   = $_POST['about_us'];
        

        if (!empty($_FILES)) {
        
			if (($_FILES['upload1']['error'] != 4) || ($_FILES['uploadlogo']['error'] != 4)) {
                $_SERVER['NOT_JSON'] = 1;
                $res = Ac_Util::uploadCompanyPhotoProcess();
            }
			
            
        }
        
        $c->save();
       
        return true;
    }

    private function getNewSubForm()
    {
        $form = new Ac_SubForm();
        //$form->setDecorators($this->subFormDecorators);
        return $form;
    }
	
	public function __toString()
    {
        $str = '
            $j("#area_l1").change(function (event) {                
                event.stopImmediatePropagation();
                $j.get("/search/get-attribute", { c:"area", f:"area_l2_postad", id: $j("#area_l1").val() },
                    function(data) {
                        $j("#area_l2").empty();
                        $j.each(data, function (index, value) {
                            $(document.createElement("option"))
                                .html(value)
                                .attr("value", index)
                                .appendTo($("#area_l2"));
                        });
                         //Entire City
					    if ($j("#area_l1").val() == "4eeae63be62d6c5978000000" || $j("#area_l1").val() == "4eeeeeeeeeeeeeeeeeeeeeee" || $j("#area_l1").val() == "4aaaaaaaaaaaaaaaaaaaaaaa") {
					        $j("#area_l2").hide();
					        $j("#st_en").hide();
					    }
					    else {
					        $j("#area_l2").show();
					        $j("#st_en").show();
					    }
                    });
           });
		   
        ';

        $this->view->JQuery()->addJavascript($str);
        return parent::__toString();
    }
}
